<template>
  <div :class="[prefixCls, `${prefixCls}--${theme}`]">
    <a-menu v-model:selectedKeys="current" mode="horizontal">
      <template v-for="item in apps" :key="item.code">
        <a-menu-item v-bind="getAttr(item.code)" @click="handleChangeApp(item)">
          <template #icon>
            <Icon :icon="item.icon" v-if="item.icon" />
          </template>
          {{ item.name }}
        </a-menu-item>
      </template>
    </a-menu>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { Menu, MenuItem } from 'ant-design-vue';

  import Icon from '/@/components/Icon';

  import { usePermission } from '/@/hooks/web/usePermission';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useGo } from '/@/hooks/web/usePage';

  import { useUserStore } from '/@/store/modules/user';
  import { propTypes } from '/@/utils/propTypes';

  export default defineComponent({
    name: 'UserApplication',
    components: {
      Icon,
      [Menu.name]: Menu,
      [MenuItem.name]: MenuItem,
    },
    props: {
      theme: propTypes.oneOf(['dark', 'light']),
    },
    setup() {
      const { prefixCls } = useDesign('layout-breadcrumb');
      const go = useGo();

      const { refreshMenu } = usePermission();
      const userStore = useUserStore();
      const apps = computed(() => userStore.getUserInfo.apps);
      const current = ref<string[]>([userStore.getCurrentApp?.code || 'system']);

      const getAttr = (code: string | number) => ({ code });

      function handleChangeApp(item) {
        if (current.value[0] === item.code) {
          return;
        }
        userStore.setCurrentApp(item);
        current.value = item.code;
        refreshMenu().then(() => {
          // 等菜单刷新完跳转
          setTimeout(() => go('/' + item.code), 1000);
        });
      }

      return { prefixCls, apps, current, getAttr, handleChangeApp };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-layout-breadcrumb';

  .@{prefix-cls} {
    display: flex;
    padding: 0 8px;
    align-items: center;

    .ant-breadcrumb-link {
      .anticon {
        margin-right: 4px;
        margin-bottom: 2px;
      }
    }

    &--light {
      .ant-breadcrumb-link {
        color: @breadcrumb-item-normal-color;

        a {
          color: rgb(0 0 0 / 65%);

          &:hover {
            color: @primary-color;
          }
        }
      }

      .ant-breadcrumb-separator {
        color: @breadcrumb-item-normal-color;
      }
    }

    &--dark {
      .ant-breadcrumb-link {
        color: rgb(255 255 255 / 60%);

        a {
          color: rgb(255 255 255 / 80%);

          &:hover {
            color: @white;
          }
        }
      }

      .ant-breadcrumb-separator,
      .anticon {
        color: rgb(255 255 255 / 80%);
      }
    }
  }
</style>
